from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SKU, GoodsCategory, SPU
from meiduo_admin.serializers.skus import SKUSerializers, GoodsCategorySerializers, SPUSpecificationSerializers
from meiduo_admin.utils import PageNum, SkuPermission


class SKUView(ModelViewSet):
    serializer_class = SKUSerializers
    queryset = SKU.objects.all()
    pagination_class = PageNum
    permission_classes = [IsAdminUser]
    permission_classes_by_action = {'create': [SkuPermission],
                                    'update': [SkuPermission],
                                    'destroy': [SkuPermission]
                                    }

    def get_permissions(self):
        try:
            # return permission_classes depending on `action`
            return [permission() for permission in self.permission_classes_by_action[self.action]]
        except KeyError:
            # action is not set return default permission_classes
            return [permission() for permission in self.permission_classes]

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            # 获取全部用户数据
            return SKU.objects.all()
        # 获取关键字查询的数据
        return SKU.objects.filter(name__contains=keyword)

    @action(methods=['get'], detail=False)
    def categories(self,request):
        # 获取三级分类信息
        categories = GoodsCategory.objects.filter(subs=None)
        ser = GoodsCategorySerializers(categories,many=True)

        return Response(ser.data)

    def specs(self,request,pk):
        # 获取spu规格表信息
        spu = SPU.objects.get(id=pk)
        specs = spu.specs.all()
        ser = SPUSpecificationSerializers(specs,many=True)
        return Response(ser.data)

